package com.approval.approvalapp.center.index;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.approval.approval.LocationService;
import com.approval.approvalapp.MainActivity;
import com.approval.approvalapp.MyAppliaction;
import com.approval.approvalapp.R;
import com.approval.approvalapp.center.adapter.CenterIndexAdapter;
import com.approval.approvalapp.center.bean.CenterIndexBean;
import com.approval.approvalapp.index.IndexFragment;
import com.approval.approvalapp.index.QdActivity;
import com.approval.approvalapp.util.ErrorBeanUtil;
import com.approval.approvalapp.util.SpUtil;
import com.approval.approvalapp.util.base.BaseFragment;
import com.approval.approvalapp.util.net.CreateJsonUtil;
import com.approval.approvalapp.util.net.NetRequsetUtil;
import com.approval.approvalapp.util.net.interfacepac.NetDownResponse;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;


/**
 * A simple {@link Fragment} subclass.
 */
public class CenterIndexFragment extends BaseFragment implements AppBarLayout.OnOffsetChangedListener, CenterIndexAdapter.Dklistener {


    @Bind(R.id.titleTv1)
    TextView titleTv1;
    @Bind(R.id.titleTv2)
    TextView titleTv2;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.erro_rl)
    RelativeLayout erroRl;
    @Bind(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.civ)
    CircleImageView civ;
    @Bind(R.id.search_iv)
    ImageView search_iv;
    @Bind(R.id.zx_iv)
    ImageView zx_iv;
    private CenterIndexAdapter adapter;
    private CenterIndexBean centerIndexBean;
    private int REQUEST_CODE = 101;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_center_index;
    }

    @Override
    public void initView(View view) {
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = this.getActivity().getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            this.getActivity().getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        Glide.with(this.getActivity()).load(SpUtil.getString(this.getActivity(), SpUtil.USER_AVATER, ""))
                .into(civ);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new CenterIndexAdapter(null, getActivity(), this);
        recyclerView.setAdapter(adapter);

        search_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(CenterIndexFragment.this.getActivity(), SearchWebActivity.class);
                CenterIndexFragment.this.startActivity(intent);
            }
        });

        zx_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(CenterIndexFragment.this.getActivity(), CaptureActivity.class);
                startActivityForResult(intent, 101);
            }
        });

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swipeRefreshLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        requestData();
                    }
                }, 1000);
            }
        });
    }


    @Override
    public void initData() {
        titleTv2.setText(SpUtil.getString(MyAppliaction.getInstance(), SpUtil.UNIT_NAME, ""));
        titleTv1.setText(SpUtil.getString(MyAppliaction.getInstance(), SpUtil.USER_RUN_NICKNAME, ""));
        swipeRefreshLayout.setRefreshing(true);
        if (!TextUtils.isEmpty(SpUtil.getString(CenterIndexFragment.this.getActivity(), SpUtil.CENCACHE, ""))) {
            erroRl.setVisibility(View.VISIBLE);

            String string = SpUtil.getString(CenterIndexFragment.this.getActivity(), SpUtil.CENCACHE, "");
            Gson gson = new Gson();
            centerIndexBean = gson.fromJson(string, CenterIndexBean.class);

            adapter.setCenterIndexBean(centerIndexBean);
            adapter.notifyDataSetChanged();


        }
        swipeRefreshLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                requestData();
            }
        }, 1000);


    }

    public void requestData() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("org_code",
                SpUtil.getString(MyAppliaction.getInstance(), SpUtil.ORG_CODE, "-1"));
        hashMap.put("region_code",
                SpUtil.getString(MyAppliaction.getInstance(), SpUtil.REGION_CODE, "-1"));
        hashMap.put("GZFW", SpUtil.getString(this.getActivity(),
                SpUtil.GZFW1, ""));


        NetRequsetUtil.getInstance().netRequestPostJson("v1/user/center_index", CreateJsonUtil.creteJsonStr(hashMap), new NetDownResponse() {
            public String TAG = getClass().getSimpleName();

            @Override
            public void success(String str) {

                Log.d("CenterIndexFragmentss", str);

                erroRl.setVisibility(View.GONE);
                Gson gson = new Gson();
                centerIndexBean = gson.fromJson(str, CenterIndexBean.class);
                String s = gson.toJson(centerIndexBean);
                SpUtil.saveString(CenterIndexFragment.this.getActivity(), SpUtil.CENCACHE, s);

                adapter.setCenterIndexBean(centerIndexBean);
                adapter.notifyDataSetChanged();

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("region_code",
                        SpUtil.getString(CenterIndexFragment.this.getActivity(),
                                SpUtil.REGION_CODE, ""));
                NetRequsetUtil.getInstance().netRequestPostJson("v1/user/get_all_pl_infos",
                        jsonObject.toString(), new NetDownResponse() {
                            @Override
                            public void success(String str) {
                                CenterIndexBean.HhvBean hhvBean = JSON.parseObject(str,
                                        CenterIndexBean.HhvBean.class);
                                if (centerIndexBean == null) {
                                    return;
                                }
                                centerIndexBean.setHhv(hhvBean);
                                if (adapter == null) {
                                    return;
                                }
                                adapter.setCenterIndexBean(centerIndexBean);
                                adapter.notifyDataSetChanged();
                            }

                            @Override
                            public void errowithresponse(String str) {

                            }

                            @Override
                            public void erro() {

                            }

                            @Override
                            public void finish() {

                            }
                        });
            }

            @Override
            public void errowithresponse(String str) {
                erroRl.setVisibility(View.VISIBLE);
            }

            @Override
            public void erro() {
                try {
                    if (swipeRefreshLayout != null) {
                        requestData();
//                        swipeRefreshLayout.setRefreshing(false);
                    }
                } catch (Exception e) {

                }
            }

            @Override
            public void finish() {
                if (swipeRefreshLayout != null) {
                    swipeRefreshLayout.setRefreshing(false);
                }
            }
        });
    }

    @OnClick(R.id.erro_rl)
    public void onViewClicked() {
        requestData();
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        if (verticalOffset == 0) {
            swipeRefreshLayout.setEnabled(true);
            toolbar.setVisibility(View.GONE);
        } else if (verticalOffset == -appBarLayout.getHeight()) {
            toolbar.setVisibility(View.VISIBLE);
        } else {
            swipeRefreshLayout.setEnabled(false);
        }

    }

    private void getLocation() {

        if (ActivityCompat.checkSelfPermission(this.getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this.getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location != null) {
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            String lstr = latitude + "";
            String longtr = longitude + "";
            String latitudestr = lstr.substring(0, 5);
            String longitudestr = longtr.substring(0, 6);

            Intent intent = new Intent(CenterIndexFragment.this.getActivity(), QdActivity.class);
            intent.putExtra("latitudestr", latitudestr);
            intent.putExtra("longitudestr", longitudestr);
            startActivity(intent);


        } else {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
        }

    }

    LocationListener locationListener = new LocationListener() {
        // Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            Log.d("MainActivity", "1");
        }

        // Provider被enable时触发此函数，比如GPS被打开
        @Override
        public void onProviderEnabled(String provider) {
            Log.d("MainActivity", "1");
        }

        // Provider被disable时触发此函数，比如GPS被关闭
        @Override
        public void onProviderDisabled(String provider) {
            Log.d("MainActivity", "1");

        }

        // 当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
        @Override
        public void onLocationChanged(Location location) {
            if (location != null) {
                Log.e("Map", "Location changed : Lat: " + location.getLatitude() + " Lng: " + location.getLongitude());
                double latitude = location.getLatitude();
                double longitude = location.getLongitude();
                String lstr = latitude + "";
                String longtr = longitude + "";
                String latitudestr = lstr.substring(0, 5);
                String longitudestr = longtr.substring(0, 6);

                Intent intent = new Intent(CenterIndexFragment.this.getActivity(), QdActivity.class);
                intent.putExtra("latitudestr", latitudestr);
                intent.putExtra("longitudestr", longitudestr);
                startActivity(intent);

            } else {
                Log.d("MainActivity", "gg");
            }
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 100:
                if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                    //gps已打开
                    locationService.start();// 定位SDK

                } else {
                    Intent i = new Intent();
                    i.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(i, 100);
                }
                break;
            case 101:
                //处理扫描结果（在界面上显示）
                if (null != data) {
                    Bundle bundle = data.getExtras();
                    if (bundle == null) {
                        return;
                    }
                    if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                        String result = bundle.getString(CodeUtils.RESULT_STRING);
                        String gwid = result.substring((result.lastIndexOf("=") + 1), result.length());
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("GWID", gwid);
//                        v1/center/sao_hui_yi_login
                        NetRequsetUtil.getInstance().netRequestPostJson("v1/center/sao_hui_yi_login",
                                jsonObject.toString(), new NetDownResponse() {
                                    @Override
                                    public void success(String str) {
                                        Toast.makeText(CenterIndexFragment.this.getActivity(), "签到成功", Toast.LENGTH_SHORT).show();
                                    }

                                    @Override
                                    public void errowithresponse(String str) {
                                        ErrorBeanUtil.getErrorMessage(str);
                                    }

                                    @Override
                                    public void erro() {

                                    }

                                    @Override
                                    public void finish() {

                                    }
                                });
                    } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                        Toast.makeText(CenterIndexFragment.this.getActivity(), "解析二维码失败", Toast.LENGTH_LONG).show();
                    }
                }
                break;
        }
    }

    private LocationManager locationManager;
    private LocationService locationService;

    @Override
    public void dk() {
        locationManager = (LocationManager) this.getActivity().getSystemService(Context.LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
//            getLocation();
            //gps已打开
            Log.d("QdActivity33", "???");
            locationService.start();// 定位SDK
        } else {
            Intent i = new Intent();
            i.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(i, 100);
        }
    }

    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                //经度
                double longitude = location.getLongitude();
                //纬度
                double latitude = location.getLatitude();


                String lstr = latitude + "";
                String longtr = longitude + "";
                String latitudestr = lstr.substring(0, 5);
                String longitudestr = longtr.substring(0, 6);

                Intent intent = new Intent(CenterIndexFragment.this.getActivity(), QdActivity.class);
                intent.putExtra("latitudestr", latitudestr);
                intent.putExtra("longitudestr", longitudestr);
                startActivity(intent);

                locationService.stop();
                locationService.unregisterListener(mListener); //注销掉监听

            }
        }

    };


    @Override
    public void onResume() {
        super.onResume();
        // TODO Auto-generated method stub
        super.onStart();
        // -----------location config ------------
        locationService = ((MyAppliaction) this.getActivity().getApplication()).locationService;
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        locationService.registerListener(mListener);
        //注册监听

        locationService.setLocationOption(locationService.getDefaultLocationClientOption());

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        locationService.stop();
        locationService.unregisterListener(mListener); //注销掉监听
    }
}
